<template>
  <div class="page product-details">
    <StoreChoice
      ref="StoreChoice"
      :current="store"
      :multipleChoice="true"
      :multipleSelectAll="false"
      @listenToStoreSelect="getSelectStoreValue"
      :statusFilter="false"
      :hasTotal="false"
      tipMsg="部分门店不符合开通条件，可联系销售人员解决"
      :reqUrl="shopReqUrl"
    />
    <userInfo ref="userInfo" @getUserInfo="getUserInfo"></userInfo>
    <contract ref="contract" :params="contractParams" :pay="payment"/>
    <div class="scroll-view">
      <customHeader class="_header" @leftCallBack="handleBack" v-if="returnBtnBag"></customHeader>
      <customHeader @leftCallBack="handleBack" v-if="!returnBtnBag"></customHeader>
      <div class="page-body" ref="pageBody" :style="{marginTop:headerheight+'px'}">
        <div class="ct-body" ref="ctBody">
          <div class="img-swipe-box">
            <mt-swipe :auto="0" :show-indicators="detailInfo.linkImages.length>1?true:false" class="img-swipe">
              <mt-swipe-item v-for="(item,index) in detailInfo.linkImages" :key="index">
                <img class="mainImg" :src="imgFormate(item)" alt />
              </mt-swipe-item>
            </mt-swipe>
            <div class="img-info">
              <p>{{detailInfo.machineToolName}}</p>
              <p>{{detailInfo.machineToolDescription}}</p>
              <p>
                <span>¥ {{detailInfo.currentPrice}}{{CommonUtil.needUnitMall(detailInfo.machineType)}}</span>
                <span>¥ {{detailInfo.originalPrice}}{{CommonUtil.needUnitMall(detailInfo.machineType)}}</span>
              </p>
            </div>
          </div>
          <ul
            class="linebar-list-num"
            v-if="CommonUtil.needCountMall(detailInfo.machineType)"
          >
            <li>
              <div class="context-left">
                <span class="main-text text-left">购买数量</span>
              </div>
              <div class="context-right">
                <div class="num-box">
                  <i
                    class="zhk-js"
                    :class="minClass ? 'activeClass' : 'disabledClass' "
                    @click="min"
                  ></i>
                  <input class="buy-num" name type="number" v-model="counter" />
                  <i
                    class="zhk-zj"
                    :class="addClass ? 'activeClass' : 'disabledClass' "
                    @click="add"
                  ></i>
                </div>
              </div>
            </li>
          </ul>
          <template v-if="CommonUtil.needShopMall(detailInfo.machineType)">
            <div class="form-title">适用门店</div>
            <ul class="form-style select-store">
              <li v-if="roleInfo.manyShopFlag" @click="handleClickSelectStore">
                <span>选择适用门店</span>
                <div>
                  <span v-if="store.length>1">
                    已选择
                    <span class="blue-text">{{store.length}}</span>家门店
                  </span>
                  <span v-else>{{store[0].selectName===null?"请选择":store[0].selectName}}</span>
                  <i class="zhk-list_rarrow"></i>
                </div>
              </li>
              <li v-else>
                <span>{{store[0].selectName}}</span>
                <div></div>
              </li>
              <li>
                <!-- <span class="tip-msg" v-if="detailInfo.addPurchasePrice">提示：每增加一个门店增收{{detailInfo.addPurchasePrice}}元</span> -->
                <span class="tip-msg" v-if="detailInfo.addPurchasePrice">
                  提示：{{detailInfo.machineType==34?'一年版':'二年版'}}基础价格{{detailInfo.currentPrice}}元，每增加一个门店增收{{detailInfo.addPurchasePrice}}元。（本定价不含运营服务费）
                </span>
                <span class="tip-msg" v-else>提示：获取会员信息，可以将门店入驻小程序或线下导入哦。</span>
              </li>
            </ul>
          </template>
          <template v-if="CommonUtil.needLinkInfo(detailInfo.machineType)">
            <div class="form-title">联系人信息</div>
            <ul class="form-style" v-show="!userInfo.linkMan">
              <li @click="showUserInfo">
                <span class="required">联系人信息</span>
                <div>
                  <i class="zhk-list_rarrow"></i>
                </div>
              </li>
            </ul>
            <ul class="recive-info" v-show="userInfo.linkMan">
              <li @click="showUserInfo">
                <div>
                  <span class="text-left">{{userInfo.linkMan}}</span>
                  <span class="text-right">{{userInfo.linkManMobile}}</span>
                </div>
                <div>
                  <p class="text-left">{{userInfo.linkManEmail}}</p>
                  <i class="zhk-list_rarrow text-right"></i>
                </div>
              </li>
            </ul>
          </template>
          <!-- 购买签约 -->
          <ul class="form-style ul-contract" v-if="jkbTypes.includes(detailInfo.machineType)">
            <li>
              <span class="required">商户名称</span>
              <div>
                <inputClear @blur="fieldValidate('supplierName')" v-model="supplierName" placeholder="请填写，用于合同签约" :maxlength="30"/>
              </div>
            </li>
            <li><span class="tip-msg">如果商户是企业或个体工商户，请务必填写营业执照上的商户名称</span></li>
            <li>
              <span class="required">签约人</span>
              <div>
                <inputClear @blur="fieldValidate('contractor')" v-model="contractor" placeholder="请填写，用于合同签约" :maxlength="10"/>
              </div>
            </li>
          </ul>
          <div class="form-title">附加信息</div>
          <ul class="form-style">
            <li>
              <span class="required">备注</span>
              <div>
                <textarea
                  @blur="fieldValidate('remarksValue')"
                  v-model="remarksValue"
                  :placeholder="CommonUtil.needLinkInfo(detailInfo.machineType)?'请注明推广诉求，产品信息，及受众群体':'选填'"
                  :maxlength="200"
                  rows="2"
                  style="height: 1.9rem;"
                ></textarea>
              </div>
            </li>
            <li>
              <span class="required">邀请码</span>
              <div>
                <inputClear
                  @blur="fieldValidate('invitationCode')"
                  v-model="invitationCode"
                  placeholder="选填"
                  :max="15"
                  :maxlength="15"
                ></inputClear>
              </div>
            </li>
          </ul>
          <div class="form-title-center">
            <i :class="isChecked?'zhk-ty':'zhk-wxz'" @click="toggleCheckbox" />
            <label>
              我已阅读并同意
              <span
                v-if="CommonUtil.isMessagePackage(detailInfo.machineType)"
                @click="linktoMessageProtol"
              >《短信推广服务在线协议》</span>
              <span v-else @click="jumpToserviceContract">《同福商家产品服务协议》</span>
            </label>
          </div>
        </div>
      </div>
      <ul class="total-buy">
        <li class>
          <p>
            合计金额：
            <span>¥ {{CommonUtil.needShopMall(detailInfo.machineType)?totalMoneyByShop:totalMoney}}</span>
          </p>
          <!-- <p @click="payment">立即购买</p> -->
          <p @click="beforePayment">立即购买</p>
        </li>
      </ul>
    </div>
    <serviceContract ref="servContract"></serviceContract>
    <messageProtocol ref="messageProtocol"></messageProtocol>
  </div>
</template>

<script>
import Vue from "vue";
import customHeader from "../../components/header/header";
import config from "../../base/profile/config.json";
import jsBridge from "../../tools/jsBridge.js";
import { Swipe, SwipeItem, Toast } from "mint-ui";
import StoreChoice from "../../components/StoreChoice/StoreChoice";
import inputClear from "../../components/inputClear/inputClear";
import serviceContract from "./serviceContract";
import messageProtocol from "./messageProtocol";
import userInfo from "./userInfo";
import contract from './contract';
Vue.component(Swipe.name, Swipe);
Vue.component(SwipeItem.name, SwipeItem);

export default {
  name: "productDetails",
  data() {
    return {
      CommonUtil: CommonUtil,
      headerheight: 0,
      roleInfo: {
        role: "",
        shopName: "",
        yzShopId: ""
      },
      remarksValue: "", //备注
      invitationCode: "", //邀请码
      remarkValue: "",
      inviteCodeValue: "",
      counter: 1, //购买数量
      totalMoney: 0,
      minClass: false,
      addClass: true,
      isChecked: true,
      store: [{ selectKey: null, selectName: null }],
      isAllStore: true,
      // packageName: "",
      // packageDescription: "",
      // currentPrice: "",
      // originalPrice: "",
      // machineToolId: "", //设备类型
      orderId: "",
      param: {},
      refuseClick: false,
      returnBtnBag: true,
      detailInfo: {
        commidyType: null,
        currentPrice: 0,
        id: null,
        linkImages: [],
        machineToolDescription: "",
        machineToolName: "",
        machineType: null,
        mainImage: "",
        originalPrice: null,
      },
      userInfo: {
        linkMan: "",
        linkManMobile: "",
        linkManEmail: "",
      },
      jkbTypes: [34, 35], //聚客宝产品集合
      supplierName: '', //商户名称
      contractor: '',    //签约人
      contractParams: {}
    };
  },
  watch: {
    counter(newValue, oldValue) {
      if (newValue <= 1) {
        if (newValue < 1) {
          this.counter = 1;
          Toast("数量超过限制范围");
        }
        this.minClass = false;
        this.addClass = true;
      } else if (newValue > 1 && newValue < 999) {
        this.minClass = true;
        this.addClass = true;
      } else {
        if (newValue > 999) {
          this.counter = 999;
          Toast("数量超过限制范围");
        }
        this.minClass = true;
        this.addClass = false;
      }
      this.totalMoney = newValue * 10000 * this.detailInfo.currentPrice / 10000;
    }
  },
  methods: {
    handleBack() {
      if (this.$refs.servContract.popupServiceVisible) {
        this.$refs.servContract.popupHide();
      } else if (this.$refs.StoreChoice.popupVisible) {
        this.$refs.StoreChoice.back();
      } else if (this.$refs.contract.popupVisible) {
        this.$refs.contract.popupHide();
      } else {
        if (String(this.$route.query.close) == "true") {
          jsBridge.closeWindow();
        } else {
          this.$router.back();
        }
      }
    },
    showUserInfo() {
      this.$refs.userInfo.popupShow();
    },
    getUserInfo(v) {
      this.userInfo = v;
    },
    //是否是大V推广套餐
    isSpreadPackage(machineType) {
      if (machineType == 25 || machineType == 26 || machineType == 27) {
        return true;
      } else {
        return false;
      }
    },
    imgFormate(v) {
      return config.shopImgUrlPrefix + v;
    },
    //打开门店选择
    handleClickSelectStore() {
      if (this.roleInfo.manyShopFlag!==undefined&&!this.roleInfo.manyShopFlag) {
        return;
      }
      this.$refs.StoreChoice.popupShow();
    },
    //门店选择回调
    getSelectStoreValue(value, storeName) {
      if (storeName === "全部门店") {
        this.isAllStore = true;
      } else {
        this.isAllStore = false;
      }
      this.store = value;
    },
    // 购买数量计数
    min() {
      if (this.counter > 1) {
        this.counter = parseInt(this.counter) - 1;
      }
    },
    add() {
      if (this.counter < 999) {
        this.counter = parseInt(this.counter) + 1;
      }
    },
    // 切换勾选协议
    toggleCheckbox() {
      this.isChecked = !this.isChecked;
    },
    encodePayInfo(string) {
      let str = string;
      let temp = str.split("&");
      let resultArray = [];
      for (let index = 0; index < temp.length; index++) {
        let item;
        if (temp[index].startsWith("sign=")) {
          item = [];
          item.push("sign");
          item.push(encodeURIComponent(temp[index].slice(5)));
        } else {
          item = temp[index].split("=");
          item[1] = encodeURIComponent(item[1]);
        }
        resultArray.push(item.join("="));
      }
      return resultArray.join("&");
    },
    beforePayment() {
      //校验门店
      if (CommonUtil.needShopMall(this.$route.query.machineType) && (this.store.length === 0 || !this.store[0].selectKey)) {
        Toast("请选择适用门店");
        return;
      }
      this.successMsg = "";//订购成功页的提示信息
      //联系人信息校验(推广套餐、码卡龙定制广告图、本地生活视频拍摄)
      if (CommonUtil.needLinkInfo(this.$route.query.machineType)) {
        this.successMsg = "我们的业务人员会在2个工作日内与您联系，请保持手机畅通";
        if (!this.userInfo.linkMan || !this.userInfo.linkManMobile || !this.userInfo.linkManEmail) {
          Toast("请填写联系人信息");
          return;
        }
      }
      let protol = "同福商家产品服务协议";
      if (CommonUtil.isMessagePackage(this.$route.query.machineType)) {
        protol = "短信推广服务在线协议"
      }
      if (!this.isChecked) {
        Toast("请阅读并同意《" + protol + "》");
        return;
      }
      /* if (!this.isNomalLetter(this.invitationCode)) {
        Toast("请输入6～15位字符，数字+字母");
        return;
      } */
      if(!this.fieldValidate()) return;
      if(this.jkbTypes.includes(this.detailInfo.machineType)) {
        this.contractParams = {
          goodsName: this.detailInfo.machineToolName,
          totalAmount: this.totalMoneyByShop,
          contractor: this.contractor,
          supplierName: this.supplierName,
          machineToolId: this.$route.query.machineType
        };
        this.$refs.contract.popupShow();
      }else {
        this.payment();
      }
    },
    // 支付接口
    payment() {
      if (this.refuseClick) {
        return;
      } else {
        let deviceNum = this.counter;
        //以所选门店数为数量
        let shopIdArr = [];
        if(CommonUtil.needShopMall(this.$route.query.machineType)){
          this.store.forEach(shop => {
            shopIdArr.push(shop.selectKey);
          });
          deviceNum = shopIdArr.length;
        }
        if (String(deviceNum).indexOf(".")!=-1) {
          Toast("请输入正确的购买数量");
          return;
        }
        this.refuseClick = true;
        const param = {
          deviceNum: deviceNum,
          inviteCode: this.invitationCode, //-邀请码
          machineToolId: this.$route.query.machineType,
          realAmount: null,
          remark: this.remarksValue, //订单备注
          selfSupplierId: null,
          shopIds: shopIdArr,
          linkMan: this.userInfo.linkMan,
          linkManMobile: this.userInfo.linkManMobile,
          linkManEmail: this.userInfo.linkManEmail,
          contractor: this.contractor,
          supplierName: this.supplierName
        };
        this.ajax({
          url: "/newapp/software/service/createServiceOrder.do",
          type: "post",
          data: param,
          controlLoading: true
        })
          .then(res => {
            this.refuseClick = false;
            if (res.success && res.resultObject) {
              this.concatVisible = false;
              this.orderId = res.resultObject.orderId;



              //0元订单直接跳转到支付成功页，不再调取支付接口
              if (res.resultObject.orderInfo === "free") {
                this.messageResult();
                this.$router.push({
                  path: "/mallList/productDetails/payResult",
                  query: {
                    type: "true",
                    toRouterNum: 1,
                    toRouterRecordNum: 1,
                    msg: this.successMsg,
                    machineType:this.$route.query.machineType,
                  }
                });
                return;
              }

              //调取app支付接口
              jsBridge.tradePay(
                {
                  payType: "alipay",
                  orderInfo: this.encodePayInfo(res.resultObject.orderInfo)
                },
                result => { 
 
                  this.refuseClick = false;
                  if (result.resultObject.resultStatus == "9000") {//成功

                    //短信推广
                    this.messageResult();


                    this.$router.push({
                      path: "/mallList/productDetails/payResult",
                      query: {
                        type: "true",
                        toRouterNum: 1,
                        toRouterRecordNum: 1,
                        msg: this.successMsg,
                        machineType:this.$route.query.machineType,
                      }
                    });
                  } else if (result.resultObject.resultStatus == "4000") {//失败
                    this.$router.push({
                      path: "/mallList/productDetails/payResult",
                      query: {
                        type: "false",
                        toRouterNum: 1,
                        toRouterRecordNum: 1
                      }
                    });
                  } else {
                    this.$router.push({
                      path: "/mallList/orderRecord/orderDetails",
                      query: { orderId: this.orderId, machineType: this.$route.query.machineType }
                    });
                  }
                }
              );
            } else {
              Toast(res.msg);
            }
          })
          .catch(err => {
            this.refuseClick = false;
            Toast(err.msg);
          });
      }
    },
    //表单校验
    checkFiled(name, value) {
      const fildRule = {
        supplierName: {
          required: true,
          reg: /^[\u4e00-\u9fa5a-zA-Z0-9()（）]{1,30}$/,
          emptyMsg: '请填写商户名称',
          errMsg: '商户名称只能填写汉字、字母、数字、中英文括号'
        },
        contractor: {
          required: true,
          reg: /^[\u4e00-\u9fa5a-zA-z0-9~!@#$%^&*()_+-={}|\[\]:";'<>?,.]{1,10}$/,
          emptyMsg: '请填写签约人',
          errMsg: '签约人只能填写填写汉字、字母、符号'
        },
        invitationCode: {
          reg: /^[a-zA-Z0-9]{6,15}$/,
          errMsg: '邀请码请输入6～15位字符，数字+字母'
        }
      }
      let rule = fildRule[name], validate = true;
      this.toastInstance && this.toastInstance.close();
      if(rule.required && !value) {
        this.toastInstance = Toast(rule.emptyMsg);
        validate = false;
      }else if(value) {
        validate = (rule.reg).test(value);
        if(!validate) {
          this.toastInstance = Toast(rule.errMsg);
        }
      }
      return validate;
    },
    // 邀请码验证特殊字符
    isNomalLetter(value) {
      let result = false;
      const test = /^[a-zA-Z0-9]+$/;
      if (value && (value.length < 6 || value.length > 15 || !test.test(value))) {
        result = false;
      } else {
        result = true;
      }
      return result;
    },
    //字段校验
    fieldValidate(fieldName) {
      let isValidate = true;
      //邀请码
      /* if (fieldName === "invitationCode") {
        const fieldValue = this.invitationCode;
        if (fieldValue) {
          if (!this.isNomalLetter(fieldValue)) {
            isValidate = false;
            Toast("请输入6～15位字符，数字+字母");
            return isValidate;
          }
        }
      } */
      let fileds = ['invitationCode'];
      if(this.jkbTypes.includes(this.detailInfo.machineType)) {
        fileds = ['supplierName', 'contractor', 'invitationCode'];
      }
      if(fieldName) {
        if(fileds.includes(fieldName)) {
          this.checkFiled(fieldName, this[fieldName])
        }
      }else {
        for(let i=0; i < fileds.length; i++) {
          isValidate = this.checkFiled(fileds[i], this[fileds[i]])
          if(!isValidate) break;
        }
        return isValidate;
      }
    },
    // 跳转到服务协议
    jumpToserviceContract() {
      this.$refs.servContract.popupShow();
    },
    // 跳转到短信服务协议
    linktoMessageProtol() {
      this.$refs.messageProtocol.popupShow();
    },
    eventListener() {
      document.getElementsByTagName("body")[0].className = "activeBody";
      if (
        this &&
        this.$refs &&
        this.$refs.ctBody &&
        this.$refs.ctBody.clientHeight
      ) {
        this.$refs.pageBody.scrollTop = this.$refs.ctBody.clientHeight;
      }
      setTimeout(() => {
        document.getElementsByTagName("body")[0].className = "";
      }, 100);
    },
    loadData() {
      this.ajax({
        url: `app/orderService/deviceDetail.do?machineToolType=` + this.$route.query.machineType,
        type: "get",
        controlLoading: false
      }).then(res => {
        if (res.success && res.resultObject) {
          this.detailInfo = res.resultObject;
          this.totalMoney = res.resultObject.currentPrice;
        } else {
          Toast(res.msg);
        }
      }).catch(err => {

      });
    },
    messageResult() {
      //短信包支付成功后，成功toast直接跳回到【短信推广】页
      if (CommonUtil.isMessagePackage(this.detailInfo.machineType)) {
        Toast("支付成功");
        this.$router.push({ path: "/messageMarketing", query: { close: true } });
        return;
      }
    }
  },
  computed: {
    //通过门店数计算的总金额
    totalMoneyByShop() {
      let orderStatus = this.$route.query.orderStatus;
      let shopPrice = this.detailInfo.addPurchasePrice || this.detailInfo.currentPrice;
      let num;
      if(this.store.length === 0 || !this.store[0].selectKey) {
        num = 0;
      }else {
        if(orderStatus==1) {
          num = Number(shopPrice)*(this.store.length);
        }else {
          num = Number(shopPrice)*(this.store.length-1) + Number(this.detailInfo.currentPrice);
        }
      }
      return num;
      /* if(orderStatus==1) {
        let num = Number(shopPrice)*(this.store.length);
        if(this.store.length === 0 || !this.store[0].selectKey) {
          num = 0;
        }
        return num;
        // return Number(shopPrice)*(this.store.length);
      }else {
        return Number(shopPrice)*(this.store.length-1) + Number(this.detailInfo.currentPrice);
      } */
      // return Number(this.detailInfo.currentPrice) * this.store.length;
    },
    shopReqUrl() {
      let url = '/newapp/applet/member/order/queryMemberOrderCityShopList.do';
      if(this.jkbTypes.includes(this.detailInfo.machineType)) {
        url = `/newapp/software/service/queryJuKeBaoOrderCityShopList.do?machineToolId=${this.detailInfo.machineType}`
      }
      return url;
    }
  },

  mounted() {
    let imgSwipeheight = document.querySelector(".img-swipe").clientHeight;
    const headerheight = document.querySelector(".header").clientHeight;
    this.headerheight = 0 - headerheight;
    imgSwipeheight = imgSwipeheight - headerheight;
    let returnBtn = this.$refs.pageBody;
    // 屏幕上下滑动切换返回按钮样式
    returnBtn.addEventListener(
      "scroll",
      () => {
        this.returnBtnBag = returnBtn.scrollTop > imgSwipeheight ? false : true;
      },
      false
    );

    window.addEventListener("resize", this.eventListener, false);
  },
  created() {
    CommonUtil.getUserInfo().then(data => {
      this.roleInfo = data;
      if (!data.manyShopFlag) {
        this.store = [{ selectKey: data.yzShopId, selectName: data.shopName }];
      }
    });
    // 获取商品详情
    this.loadData();
  },
  destroyed() {
    window.removeEventListener("resize", this.eventListener, false);
    this.concatTimer && window.clearInterval(this.concatTimer);
  },
  components: {
    customHeader,
    inputClear,
    serviceContract,
    messageProtocol,
    StoreChoice,
    userInfo,
    contract
  }
};
</script>

<style lang='scss' scoped>
@import "mall";
</style>
<style lang='scss'>
.mint-swipe-indicator {
  background: #fff;
  opacity: 0.7;
}
.mint-swipe-indicators {
  .mint-swipe-indicator.is-active {
    background: #e02424 !important;
  }
}
</style>